import { api } from "@/api";
import { useMyContext } from "@/hooks";
import action from "@/store/action";
import { Switch } from "antd";
import { useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import BulletScreen, { StyledBullet } from "rc-bullets";
import styled from "styled-components";
import { convertImgUrl } from "@/utils/MyFun";

const Styled = styled.div`
  overflow: hidden;
  height: 100vh;
  left: 0rem;
  right: 0rem;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  button {
    cursor: pointer;
    color: #fff;
    background-color: transparent;
    border: 1px solid #fff;
    border-radius: 15px;
  }
  .box {
    width: 105rem;
    border: 1px solid #fff;
    border-radius: 5px;
    animation: to-big 1s;
    padding: 3rem;
    z-index: 11;
    color: #fff;
    h2 {
      text-align: center;
      margin-bottom: 15px;
    }
    .sub {
      margin-bottom: 10px;
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      input {
        color: #fff;
        border-radius: 15px;
        width: 75%;
        height: 100%;
        background-color: transparent;
        border: 1px solid #fff;
        padding: 3px 5px;
        &::-webkit-input-placeholder {
          color: #fff;
        }
      }
      button {
        margin-left: 5px;
        width: 20%;
        height: 100%;
        padding: 5px;
        animation: enter 1s;
      }
    }
    ul {
      li {
        margin-bottom: 15px;
        display: flex;
        align-items: center;
      }
      .btn {
        padding: 5px 8px;
        margin-right: 10px;
      }
    }
  }
  .screen {
    position: absolute;
    top: 0;
    left: 0;
    color: #fff;
    height: 100vh;
    width: 100%;
  }

  @keyframes to-big {
    0% {
      transform: scale(0);
    }
    100% {
      transform: scale(1);
    }
  }
  @keyframes enter {
    0% {
      opacity: 0.7;
      transform: translateX(2000px) scale(0.7);
    }
    80% {
      opacity: 0.7;
      transform: translateY(0px) scale(0.7);
    }
    100% {
      opacity: 1;
      transform: scale(1);
    }
  }
`;
//选中的央视
const rejectclass = ["selfswtich-uncheck", "selfswtich-check"];

const Message = () => {
  //弹幕容器
  const [screen, setScreen] = useState(null);
  const dispatch = useDispatch();
  const { messageApi } = useMyContext();
  const {
    appStore: {
      blogInfo: { page_list = [] },
    },
    userStore,
  } = useSelector((state) => ({
    appStore: state.app,
    userStore: state.user,
  }));

  // 弹幕列表
  let [danmus, setDanmus] = useState([
    {
      avatar: "https://www.bing.com/rp/ar_9isCNU2Q-VG1yEDDHnx8HAFQ.png",
      content: "大家好，我是作者，欢迎给我点一颗 Star!",
      nickname: "阵、雨",
    },
  ]);
  // 设置一下switch自定义样式
  const [selfClass, setselfClass] = useState(
    rejectclass != undefined ? rejectclass[0] : undefined
  );
  let [content, setContent] = useState("");
  const [showBtn, setShowBtn] = useState(false);
  const [dmRef, setDmRef] = useState(null); // 弹幕 ref 对象
  const [isHide, setIsHide] = useState(false); // 隐藏弹幕
  const [isLoop, setIsLoop] = useState(false); // 循环播放

  const coverStyle = useMemo(() => {
    const page = page_list.find((e) => e.label === "message");
    return page
      ? { background: `url('${page?.cover}') center center / cover no-repeat` }
      : {
          background: `url("https://static.talkxj.com/config/83be0017d7f1a29441e33083e7706936.jpg") center center / cover no-repeat`,
        };
  }, [page_list]);

  async function send() {
    if (!userStore.userInfo.id) {
      messageApi.info("请先登录~");
      dispatch(action.app.setLoginFlag(true));
      return;
    }
    if (!content.trim()) {
      messageApi.info("请输入~");
      return;
    }
    try {
      const data = {
        avatar: userStore.userInfo.avatar,
        nickname: userStore.userInfo.nickname,
        content,
      };
      await api.saveMessage(data);
      //重新获取最新数据
      const res = await api.getMessages();
      setDanmus([...danmus, ...res.data]);
      setContent("");
    } catch (error) {}
  }

  useEffect(() => {
    (async () => {
      const res = await api.getMessages();
      setDanmus([...danmus, ...res.data]);
    })();
  }, []);
  //初始化弹幕容器
  useEffect(() => {
    // 给页面中某个元素初始化弹幕屏幕，一般为一个大区块。此处的配置项全局生效
    let s = new BulletScreen(".screen", { duration: 20 });
    // or
    // let s=new BulletScreen(document.querySelector('.screen));
    setScreen(s);
  }, []);

  useEffect(() => {
    screen &&
      danmus.forEach((item) => {
        screen.push(
          <StyledBullet
            head={convertImgUrl(item.avatar)}
            msg={item.content}
            backgroundColor={"#00000060"}
            size="large"
          />,
          { loopCount: isLoop }
        );
      });
  }, [danmus, isLoop]);

  return (
    <Styled className="banner-fade-down" style={coverStyle}>
      {/* 弹幕输入框 */}
      <div className="box">
        <h2>留言板</h2>
        <div className="sub">
          <input
            value={content}
            type="text"
            placeholder="请说点什么吧"
            onFocus={() => setShowBtn(true)}
            onChange={(e) => setContent(e.target.value)}
          />
          {showBtn ? <button onClick={send}>提交</button> : null}
        </div>
        <ul>
          <li>
            循环播放：
            <Switch
              className={selfClass}
              onChange={(checked) => {
                if (selfClass != undefined) {
                  //没有设置的时候不会报错，显示默认的蓝色
                  if (checked) {
                    setselfClass(rejectclass[1]);
                  } else {
                    setselfClass(rejectclass[0]);
                  }
                }
                if (checked) {
                  setIsLoop("infinite");
                } else {
                  setIsLoop(1);
                }
              }}
            />
          </li>
          <li>
            操作弹幕：
            <button className="btn" onClick={() => screen.resume()}>
              播放
            </button>
            <button className="btn" onClick={() => screen.pause()}>
              暂停
            </button>
          </li>
          <li>
            隐藏弹幕：
            <Switch
              checked={isHide}
              onChange={(bol) => {
                if (bol !== true) {
                  setIsHide(bol);
                  screen.show();
                } else {
                  setIsHide(bol);
                  screen.hide();
                }
              }}
            />
          </li>
        </ul>
      </div>
      <div className="screen"></div>
    </Styled>
  );
};

export default Message;
